import * as PIXI from 'pixi.js'
import { PixiComponent } from '@inlet/react-pixi'

function onDragStart(event) {
  // store a reference to the data
  // the reason for this is because of multitouch
  // we want to track the movement of this particular touch
  this.data = event.data
  this.dragging = true
  this.oldPosition = this.data.getLocalPosition(this.parent)
}

function onDragEnd() {
  this.dragging = false
  this.data = null
}

function onDragMove() {
  if (this.dragging) {
    const newPosition = this.data.getLocalPosition(this.parent)
    this.setCoordinate({
      x: this.x + (newPosition.x - this.oldPosition.x),
      y: this.y + (newPosition.y - this.oldPosition.y),
    })
    this.oldPosition = newPosition
  }
}

export default PixiComponent('Pan_container', {
  create: () => new PIXI.Container(),
  didMount: () => {},
  willUnmount: () => {},
  applyProps: (instance, oldProps, newProps) => {
    const {
      pan,
      cursor,
      interactive,
      setCoordinate,
      x,
      y,
    } = newProps
    instance.interactive = interactive
    instance.setCoordinate = setCoordinate
    instance.x = x
    instance.y = y
    instance.cursor = cursor
    instance.removeAllListeners()
    if (pan === true) {
      instance
        .on('pointerdown', onDragStart)
        .on('pointerup', onDragEnd)
        .on('pointerupoutside', onDragEnd)
        .on('pointermove', onDragMove)
    }
  },
})
